#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int nr = 0;
int nw = 0;
int valor = 0;
pthread_rwlock_t       rwlock;

void* readerf();
void* writerf();

int main(int argc, char *argv[])
{
      int i,j;
      int n,m; // Numero de Readers e Writers, respectivamente
      n = *argv[argc-2]-48;
      m = *argv[argc-1]-48;
      
      pthread_t reader[n]; // threads reader
      pthread_t writer[m]; // threads writer
     
      pthread_rwlock_init(&rwlock, NULL);
   
      for (j = 0; j < m; j++)
	{
	  if(pthread_create(&writer[j], 0, writerf, NULL))
	    {
	      perror("Escritor nao criado!");
	      exit(1);							
	    }
	}
	
      for (i = 0; i < n; i++)
	{
	  if(pthread_create(&reader[i], 0, readerf, NULL))
	    { 
	      perror("Leitor nao criado!");
	      exit(1);							
	    }
	}
       

      
      for (i = 0; i < n; i++)
	{
	  pthread_join(reader[i], NULL);
	}
      
      for (j = 0; j < m; j++)
	{
	  pthread_join(writer[j], NULL);
	}
    
      pthread_rwlock_destroy(&rwlock);


      pthread_exit(NULL);
      return EXIT_SUCCESS;
}

void* readerf()			
{
    
    pthread_rwlock_rdlock(&rwlock);
    
    nr = nr + 1;

    printf("Leitor esta lendo %d... (%d w - %d r)\n",valor,nw,nr);
    
    if(rand()%1) sleep(1);
    
  
    nr = nr - 1;
    
    printf("Leitor leu \n"); 
    pthread_rwlock_unlock(&rwlock);
    
    return 0;
}

void* writerf()		
{
    pthread_rwlock_wrlock(&rwlock);
    
    nw = nw + 1;
    
    valor = (rand()%100)+1;
    printf("Escritor escreveu %d... (%d w - %d r)\n",valor,nw,nr);
    sleep(rand()%5);  
    nw = nw - 1;
    
    pthread_rwlock_unlock(&rwlock);

    return 0;
}

